package com.audaque.springboot.foshanupload.web.springsecuritycas.service.impl;

import com.audaque.springboot.foshanupload.web.springsecuritycas.model.Admin;
import com.audaque.springboot.foshanupload.web.springsecuritycas.model.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 为认证和鉴权提供基础资料：根据用户名查用户的账户、密码、角色、权限
 */
@Slf4j
@Service
public class MyUserDetailServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {
/*
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate redisTemplate;*/

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {

        String username = token.getName();
        Admin admin = new Admin();
        // admin = adminMapper.selectOne(new LambdaQueryWrapper<Admin>().eq(Admin::getUsername, username));=adminMapper.selectOne(new LambdaQueryWrapper<Admin>().eq(Admin::getUsername, username));
        admin.setUsername(username);//admin
        admin.setPassword("$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2");
        log.debug("admin:{}", admin);
/*        if (admin == null)
            throw new UsernameNotFoundException("用户名不存在");*/
        SecurityUser securityUser = new SecurityUser();


        List<String> permissionList = new ArrayList<>();

    /*    //如果redis不存在该用户的权限
        if (!redisTemplate.hasKey("permission_" + admin.getUid())) {
            //添加权限
            List<Role> roleList = roleMapper.getRolesByAdminId(admin.getUid());
            permissionList = roleList.stream().map(role -> role.getRoleName()).collect(Collectors.toList());
            log.debug("从数据库中查询到用户的权限为{}", permissionList);
        } else {

            permissionList = (List<String>) redisTemplate.opsForValue().get("permission_" + admin.getUid());
            log.debug("从redis中查询到用户的权限为{}", permissionList);
        }*/

        permissionList.add("USER");
        permissionList.add("ROLE_LOGIN");
        securityUser.setPermissionValueList(permissionList);
        securityUser.setCurrentUserInfo(admin);
        log.debug("用户的权限为{}", permissionList);
        return securityUser;
    }
}

